package cn.pugle.base.uri_encode;

import cn.pugle.encrypt.CryptoUtils;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtil {
    public static String encodeBase64(byte[] binaryData, String charset)
            throws UnsupportedEncodingException {
        return new String(Base64.encodeBase64(binaryData), charset);
    }

    public static String encodeBase64(byte[] binaryData)
            throws UnsupportedEncodingException {
        return new String(Base64.encodeBase64(binaryData));
    }

    /**
     * 将BASE64字符串恢复为二进制数据
     *
     * @param base64String
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] decodeBase64(String base64String, String charset)
            throws UnsupportedEncodingException {
        return Base64.decodeBase64(base64String.getBytes(charset));
    }

    /**
     * sha 加密
     *
     * @param source
     * @param key
     * @return
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static byte[] sha(String source, String key)
            throws InvalidKeyException, UnsupportedEncodingException,
            NoSuchAlgorithmException {
        // SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);

        byte[] data = key.getBytes("UTF-8");
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance("HmacSHA1");
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = source.getBytes("UTF-8");
        // 完成 Mac 操作
        return mac.doFinal(text);

    }

    public static void main(String[] args) throws Exception {
        byte[] sha = sha("thisisdata", "thisiskey");
        System.out.println(encodeBase64(sha, "UTF-8"));
        System.out.println(new String(java.util.Base64.getEncoder().encode(sha)));
    }
}
